using CfgTable;

namespace IQIGame.Onigao.GamePlay
{
    public class UIN_CostItem : UIN_OneItem
    {
        #region fields & properties
        private int itemCid = -1;
        private int numCost = -1;
        private bool isShowHavingNum = true;

        private UIMsgDispatcher currMsgDispatcher => this._msgDispatcher as UIMsgDispatcher;
        #endregion

        protected override void BeforeInit()
        {
            base.BeforeInit();
        }

        protected override void OnDispose()
        {
            this.ClearData();
            base.OnDispose();
        }

        protected override void AddMsgListeners()
        {
            currMsgDispatcher.AddListener<int>(MsgEventType.OneItemChanged, this.OnMsgOneItemChanged);
        }

        void OnMsgOneItemChanged(int cid)
        {
            if (cid == this.itemCid)
            {
                this.ViewNum(this.numCost);
            }
        }

        public new void Show(int itemCid, int numCost)
        {
            this.Show(itemCid, numCost, true);
        }

        public void ShowCostAsCount(int itemCid, int numCost)
        {
            this.Show(itemCid, numCost, false);
        }

        private void Show(int itemCid, int numCost, bool isShowHavingNum)
        {
            CfgItem cfgItem = TableCenter.item.Get(itemCid);
            bool isOkey = base.Show(cfgItem);
            if (!isOkey)
            {
                return;
            }

            this.SetData(itemCid, numCost, isShowHavingNum);
            this.ViewNum(this.numCost);
        }

        private void SetData(int itemCid, int numCost, bool isShowHavingNum)
        {
            this.itemCid = itemCid;
            this.numCost = numCost;
            this.isShowHavingNum = isShowHavingNum;
        }

        private void ClearData()
        {
            this.itemCid = -1;
            this.numCost = -1;
            this.isShowHavingNum = true;
        }

        void ViewNum(int numCost)
        {
            if (this.isShowHavingNum)
            {
                int numHave = ItemModule.Instance.GetNum(this.itemCid);
                this.SetCost(numHave, numCost, true);
            }
            else
            {
                this.SetCount(numCost, true);
            }
        }
    }
}
